package handler

import (
	"encoding/json"
	"github.com/xiyoufang/cloud-syncer/internal/env"
	"github.com/xiyoufang/cloud-syncer/internal/http/model"
	"github.com/xiyoufang/cloud-syncer/internal/version"
	"net/http"
)

func OverviewHandler(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")
	var req model.PaginateReq
	if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
		env.Logger().Error(err.Error())
		http.Error(w, "Invalid request payload", http.StatusBadRequest)
		return
	}
	syncStats, err := env.Repository().GetSyncStats()
	if err != nil {
		env.Logger().Error(err.Error())
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	fileStats, err := env.Repository().GetFileStats()
	if err != nil {
		env.Logger().Error(err.Error())
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	response := model.ResponseBodyEntity{
		Code:    "OK",
		Message: "success",
		Data: model.OverviewVO{
			Version:   version.Full(),
			SyncStats: syncStats,
			FileStats: fileStats,
			Config:    buildConfigVO(),
		},
	}
	if err = json.NewEncoder(w).Encode(response); err != nil {
		env.Logger().Error(err.Error())
		http.Error(w, "Failed to encode response", http.StatusInternalServerError)
		return
	}
}

// buildConfigVO 将系统的配置转成界面显示的配置
func buildConfigVO() model.ConfigVO {
	config := env.Config()
	configVO := model.ConfigVO{
		Syncer: config.Syncer,
	}
	configVO.Sync.Interval = config.Sync.Interval
	configVO.Sync.Excludes = config.Sync.Excludes
	for _, path := range config.Sync.Paths {
		configVO.Sync.Paths = append(configVO.Sync.Paths, struct {
			Local  string `json:"local"`
			Remote string `json:"remote"`
		}{Local: path.Local, Remote: path.Remote})
	}
	configVO.Http.Addr = config.Http.Addr
	configVO.Http.Port = config.Http.Port
	configVO.Http.Username = config.Http.Username
	configVO.Http.SessionTimeout = config.Http.SessionTimeout
	configVO.Db.Driver = config.Db.Driver
	configVO.Db.DataSource = config.Db.DataSource
	configVO.S3.Region = config.S3.Region
	configVO.S3.BucketName = config.S3.BucketName
	configVO.Oss.Endpoint = config.Oss.Endpoint
	configVO.Oss.BucketName = config.Oss.BucketName
	return configVO
}
